<script>
import { add, giveMenu, page, remove, update, updateStatus } from "@/views/superAdmin/role/api";
import { globalLoading, handleTree } from "@/utils/service";
import { getMenuIdsByRoleId, getMenuList } from "@/views/superAdmin/menu/api";
import { hasPermission } from "@/utils/auth";
import { getOptions } from "@/api/robot/task";
import { getRobotTask } from "@/api/admin/role";
import { assignRoleRobotTask } from "@/api/admin/permission";

export default {
  name: "roleV2",
  watch: {
    "dialog2.treeFilterText": {
      handler(val) {
        this.$refs.robotTaskOptions.filter(val);
      }
    }
  },
  data() {
    return {
      table: {
        /* 选中行数据 */
        sRows: [],
        data: [],
        pageNo: 1,
        pages: 0,
        pageSize: 10,
        pageCount: 0,
        loading: false
      },
      query: {
        name: ""
      },
      dialog: {
        title: "添加角色",
        visible: false,
        form: {
          id: undefined,
          name: "",
          accountNum: 1000,
          remark: ""
        },
        rules: {
          name: [
            { required: true, message: "请输入名称", trigger: "blur" },
            { min: 2, max: 30, message: "长度在 2 到 20 个字符", trigger: "blur" }
          ],
          accountNum: [
            { required: true, message: "请输入可开放的账号数量", trigger: "blur" },
            {
              validator: function(rule, value, callback) {
                if (value < 1 || value > 99999) {
                  callback(new Error("账号数量在 1 ~ 99999 之间"));
                }
                callback();
              }, trigger: "blur"
            }
          ]
        }
      },
      dialog1: {
        visible: false,
        menuExpand: false,
        menuNodeAll: false,
        checkStrictly: true,
        menuOptions: [],
        roleName: "",
        roleId: undefined
      },
      dialog2: {
        visible: false,
        roleName: "",
        roleId: undefined,
        treeLoading: true,
        treeFilterText: ""
      },
      options: {
        robotTask: []
      }
    };
  },
  created() {
    this.page();
  },
  methods: {
    hasPermission,
    page() {
      if (!hasPermission("role.query")) {
        this.$message.warning("您没有权限获取表格数据");
        return;
      }
      let p = {
        pageNo: this.table.pageNo,
        pageSize: this.table.pageSize,
        name: this.query.name
      };
      this.table.loading = true;
      page(this, p, function(r) {
        this.table.data = r.list;
        this.table.pageNo = r.pageNo;
        this.table.pageSize = r.pageSize;
        this.table.pageCount = r.total;
        this.table.pages = r.pages;
      }.bind(this), function(f) {
        this.table.loading = false;
      }.bind(this));
    },
    handleAdd() {
      this.dialog.form.id = undefined;
      this.dialog.form.name = "";
      this.dialog.form.accountNum = 1000;
      this.dialog.form.remark = "";
      this.dialog.title = "添加角色";
      this.dialog.visible = true;
    },
    handleUpdate(row) {
      this.dialog.form.id = row.id;
      this.dialog.form.name = row.roleName;
      this.dialog.form.accountNum = row.accountNum;
      this.dialog.form.remark = row.remark || "";
      this.dialog.title = "编辑角色";
      this.dialog.visible = true;
    },
    handleDelete(idList) {
      const loading = globalLoading(this);
      remove(this, idList, function(r) {
        this.page();
      }.bind(this), function(f) {
        loading.close();
      }.bind(this));
    },
    commitForm() {
      let sFunc = function(r) {
        this.page();
      }.bind(this);
      let fFunc = function(f) {
        this.dialog.visible = false;
        loading.close();
      }.bind(this);
      let r = false;
      this.$refs["baseForm"].validate((valid) => {
        r = valid;
        return valid;
      });
      if (!r) {
        return;
      }
      const loading = globalLoading(this);
      if (this.dialog.form.id) {
        update(this, this.dialog.form, sFunc, fFunc);
      } else {
        add(this, this.dialog.form, sFunc, fFunc);
      }
    },
    commitForm1() {
      let menuIds = [...this.$refs.menuOptions.getCheckedKeys(), ...this.$refs.menuOptions.getHalfCheckedKeys()];
      giveMenu(this.dialog1.roleId, menuIds).then(res => {
        this.$message.success("操作成功");
        this.dialog1.visible = false;
      }).catch(err => {
        console.log(err.message);
      });
    },
    robotTaskTreeFilter(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    assignRobotTask() {
      let loading = globalLoading(this);
      assignRoleRobotTask(this.dialog2.roleId, this.$refs.robotTaskOptions.getCheckedKeys())
        .then(res => {
          this.$message.success("操作成功");
          this.dialog2.visible = false;
        }).finally(() => {
        loading.close();
      });
    },
    resetQuery() {
      this.query.name = "";
      this.page();
    },
    sRowChange(v) {
      this.table.sRows = v;
    },
    pageChange(v) {
      this.table.pageNo = v;
      this.page();
    },
    updateStatus(id, status) {
      updateStatus({ roleId: id, status: status }).then(r => {
        this.$message.success("操作成功");
      }).catch(err => {
        console.log(err);
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.dialog1.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menuOptions.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menuOptions.setCheckedNodes(value ? this.dialog1.menuOptions : []);
    },
    openMenuOptions(row) {
      this.dialog1.roleName = row.roleName;
      this.dialog1.roleId = row.id;
      this.dialog1.visible = true;
      this.getMenuOptions(row.id);
    },
    openTaskOptions(row) {
      this.dialog2.roleName = row.roleName;
      this.dialog2.roleId = row.id;
      this.dialog2.visible = true;
    },
    async optionDialog2() {
      this.dialog2.treeLoading = true;
      await getOptions().then(async res => {
        this.options.robotTask = res;
        await getRobotTask(this.dialog2.roleId).then(res2 => {
          this.$refs.robotTaskOptions.setCheckedKeys(res2.map(t => t.taskId));
        }).finally(() => {
          this.dialog2.treeLoading = false;
        });
      });
    },
    getMenuOptions(roleId) {
      let _ = this;
      getMenuList().then(res => {
        _.$refs.menuOptions.setCheckedKeys([]);
        _.dialog1.menuOptions = handleTree(res, "id", "parentId", "children", -1);
        getMenuIdsByRoleId(roleId).then(res1 => {
          // 设置为严格，避免设置父节点自动选中子节点，解决半选中问题
          _.dialog1.checkStrictly = true;
          this.$nextTick(() => {
            _.$refs.menuOptions.setCheckedKeys(res1);
          });
          this.$nextTick(() => {
            _.dialog1.checkStrictly = false;
          });
        });
      });
    }
  }
};
</script>

<template>
  <div style="margin: 20px 0">
    <div class="header">
      <el-form :model="query" ref="queryForm" size="mini" :inline="true">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="query.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="page">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button v-permission="'role.create'" size="mini" icon="el-icon-plus" type="primary" plain @click="handleAdd">
        创建新角色
      </el-button>
      <el-popconfirm
        v-permission="'role.delete'"
        style="margin-left: 10px"
        title="确认删除选中内容吗"
        @confirm="handleDelete(table.sRows.map(i => i.id))"
      >
        <el-button :disabled="table.sRows.length===0" slot="reference" size="mini" icon="el-icon-delete" type="danger"
                   plain>删除选中角色
        </el-button>
      </el-popconfirm>

    </div>

    <div class="main">
      <el-table
        :row-style="{height:'20px'}"
        :cell-style="{padding:'0px'}"
        :loading=table.loading
        :data="table.data"
        :stripe=true
        :border=true
        style="width: 100%;"
        @selection-change="sRowChange"
      >
        <el-table-column
          type="selection"
          width="55"
        >
        </el-table-column>

        <el-table-column
          prop="id"
          label="编号"
        >
        </el-table-column>

        <el-table-column
          prop="roleName"
          label="名称"
          align="center"
          width="300px"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          prop="accountNum"
          label="可开放账号数量"
          align="center"
          width="120px"
        >
        </el-table-column>

        <el-table-column
          width="65px"
          align="center"
          prop="status"
          label="状态">
          <template slot-scope="scope">
            <el-switch
              :disabled="!hasPermission('role.update')"
              v-if="scope.row.status === -1 || scope.row.status === 1"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=-1
              @change="updateStatus(scope.row.id,scope.row.status)"
            >
            </el-switch>
            <span v-else>未知</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="remark"
          label="备注"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          prop="createTime"
          width="160px"
          align="center"
          label="创建时间">
        </el-table-column>

        <el-table-column
          prop="updateTime"
          width="160px"
          align="center"
          label="修改时间"
        >
        </el-table-column>

        <el-table-column
          width="250"
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button v-permission="'role.update'" size="mini" type="text" @click="handleUpdate(scope.row)">编辑
            </el-button>
            <el-button v-permission="'role.giveMenu'" size="mini" type="text" style="color: #2ed573"
                       @click="openMenuOptions(scope.row)">
              菜单权限
            </el-button>
            <el-button size="mini" type="text" @click="openTaskOptions(scope.row)">
              任务权限
            </el-button>
            <el-popconfirm
              v-permission="'role.delete'"
              style="margin-left: 10px"
              title="删除此内容吗？"
              @confirm="handleDelete([scope.row.id])"
            >
              <el-button size="mini" type="text" slot="reference" style="color: #ff6b81">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer">
      <div style="text-align: center">
        <el-pagination
          background
          :page-size="table.pageSize"
          layout="sizes, prev, pager, next, jumper,->,total"
          :total="table.pageCount"
          :page-count="table.pages"
          :current-page="table.pageNo"
          @current-change="pageChange"
        >
        </el-pagination>
      </div>

    </div>

    <!--  弹出层  -->
    <div>
      <!-- 编辑基础的角色信息 -->
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :close-on-click-modal="false"
        width="30%"
      >
        <el-form :model="dialog.form" ref="baseForm" :rules="dialog.rules" size="mini" label-suffix=" : "
                 label-position="left">
          <el-form-item label="名称" prop="name">
            <el-input
              style="width: 450px"
              v-model="dialog.form.name"
              placeholder="请输入名称"
              maxlength="20"
              show-word-limit>
            </el-input>
          </el-form-item>
          <el-form-item label="可开放账号数量" prop="accountNum">
            <el-input-number v-model="dialog.form.accountNum" :min="1" :max="99999"></el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              show-word-limit
              maxlength="255"
              :autosize="true"
              placeholder="请输入备注"
              v-model="dialog.form.remark">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.visible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="commitForm" size="small">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑菜单权限信息 -->
      <el-dialog
        :visible.sync="dialog1.visible"
        :close-on-click-modal="false"
        :destroy-on-close=true
        width="500px"

      >
        <el-form :model="dialog1.form" label-suffix=" : " size="mini" ref="dialog1Form">
          <el-form-item label="编号">
            <el-input style="width: 400px" v-model="dialog1.roleId" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input style="width: 400px" v-model="dialog1.roleName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="菜单权限">
            <el-checkbox v-model="dialog1.menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
            <el-checkbox v-model="dialog1.menuNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
            <el-tree class="tree-border" :data="dialog1.menuOptions" show-checkbox
                     ref="menuOptions" node-key="id" empty-text="加载中,请稍后"
                     :props="{label: 'menuName',children: 'children'}"
                     :check-strictly="dialog1.checkStrictly"
            >
            </el-tree>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog1.visible = false" size="small">取 消</el-button>
          <el-button type="primary" size="small" @click="commitForm1">确 定</el-button>
        </div>
      </el-dialog>

      <!--  编辑任务权限信息    -->
      <el-dialog
        @opened="optionDialog2"
        :visible.sync="dialog2.visible"
        :close-on-click-modal="false"
        :destroy-on-close=true
        width="700px"
      >
        <el-form :model="dialog2.form" label-suffix=" : " size="mini" ref="dialog1Form">
          <el-form-item label="编号">
            <el-input style="width: 400px" v-model="dialog2.roleId" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input style="width: 400px" v-model="dialog2.roleName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="自动化任务">
            <el-input
              placeholder="输入关键字进行过滤"
              v-model="dialog2.treeFilterText">
            </el-input>
            <el-tree
              :filter-node-method="robotTaskTreeFilter"
              v-loading="dialog2.treeLoading"
              class="tree-border"
              :data="options.robotTask" show-checkbox
              ref="robotTaskOptions" node-key="id" empty-text="加载中,请稍后"
              :props="{label: 'name'}"
              :check-strictly="true"
            >
            </el-tree>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog2.visible = false" size="small">取 消</el-button>
          <el-button type="primary" size="small" @click="assignRobotTask">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.main {
  margin: 10px 0
}
</style>